package org.lemon.cla.serviceImp;

import org.lemon.cla.pojo.User;
import org.lemon.cla.service.IUserService;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; // 确保导入 BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import org.springframework.security.core.authority.SimpleGrantedAuthority; // 确保导入 SimpleGrantedAuthority

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final IUserService userService;
    private final PasswordEncoder passwordEncoder;

    public UserDetailsServiceImpl(IUserService userService, @Lazy PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 尝试从数据库加载用户
        User user = userService.getUserByUsername(username);

        if (user != null) {
            // 如果从数据库找到了用户，直接返回
            return user;
        }

        // --- 调试后门：如果数据库未找到，尝试硬编码用户 ---
        if ("testuser".equals(username)) {

            return new org.springframework.security.core.userdetails.User(
                    "testuser",
                    passwordEncoder.encode("password"),
                    Collections.singletonList(new SimpleGrantedAuthority("ROLE_学生"))
            );
        } else if ("admin".equals(username)) {
            return new org.springframework.security.core.userdetails.User(
                    "admin",
                    passwordEncoder.encode("adminpass"),
                    List.of(new SimpleGrantedAuthority("ROLE_管理员"), new SimpleGrantedAuthority("ROLE_学生"))
            );
        }
        // --- 调试后门结束 ---
        throw new UsernameNotFoundException("用户不存在：" + username);
    }
}